#include "medicineselectdialog.h"
#include "../../network/networkclient.h"
#include <QLabel>
#include <QMessageBox>
#include <QHeaderView>

MedicineSelectDialog::MedicineSelectDialog(QWidget *parent) :
    QDialog(parent),
    m_selectedMedicine() {
    setupUI();
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &MedicineSelectDialog::onMessageReceived);
    
    // 加载所有药物
    loadMedicines();
}

MedicineSelectDialog::~MedicineSelectDialog() {
}

void MedicineSelectDialog::setupUI() {
    setWindowTitle("选择药物");
    setMinimumSize(900, 600);
    
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    
    // 搜索栏
    QHBoxLayout* searchLayout = new QHBoxLayout();
    QLabel* searchLabel = new QLabel("药物名称:");
    m_searchEdit = new QLineEdit();
    m_searchEdit->setPlaceholderText("输入药物名称搜索...");
    m_searchButton = new QPushButton("🔍 搜索");
    m_searchButton->setStyleSheet(
        "QPushButton { background-color: #07C160; color: white; padding: 8px 16px; border-radius: 4px; }"
        "QPushButton:hover { background-color: #06AD56; }");
    
    searchLayout->addWidget(searchLabel);
    searchLayout->addWidget(m_searchEdit);
    searchLayout->addWidget(m_searchButton);
    mainLayout->addLayout(searchLayout);
    
    // 药物列表
    m_medicineTable = new QTableWidget();
    m_medicineTable->setColumnCount(5);
    m_medicineTable->setHorizontalHeaderLabels({"ID", "药物名称", "规格", "用法用量", "注意事项"});
    m_medicineTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_medicineTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_medicineTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    m_medicineTable->setColumnWidth(0, 60);
    m_medicineTable->setColumnWidth(1, 150);
    m_medicineTable->setColumnWidth(2, 120);
    m_medicineTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
    m_medicineTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Stretch);
    m_medicineTable->verticalHeader()->setVisible(false);
    
    mainLayout->addWidget(m_medicineTable);
    
    // 提示
    QLabel* tipLabel = new QLabel("💡 提示：双击药物行可快速选择，或选中后点击\"确定\"按钮");
    tipLabel->setStyleSheet("color: #999; font-size: 12px; padding: 5px;");
    mainLayout->addWidget(tipLabel);
    
    // 按钮栏
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    
    m_selectButton = new QPushButton("✓ 确定");
    m_selectButton->setStyleSheet(
        "QPushButton { background-color: #07C160; color: white; padding: 10px 24px; border-radius: 4px; font-weight: bold; }"
        "QPushButton:hover { background-color: #06AD56; }");
    
    m_cancelButton = new QPushButton("✗ 取消");
    m_cancelButton->setStyleSheet(
        "QPushButton { background-color: #F0F0F0; color: #666; padding: 10px 24px; border-radius: 4px; }"
        "QPushButton:hover { background-color: #E0E0E0; }");
    
    buttonLayout->addWidget(m_selectButton);
    buttonLayout->addWidget(m_cancelButton);
    mainLayout->addLayout(buttonLayout);
    
    // 连接信号
    connect(m_searchButton, &QPushButton::clicked, this, &MedicineSelectDialog::onSearchClicked);
    connect(m_searchEdit, &QLineEdit::returnPressed, this, &MedicineSelectDialog::onSearchClicked);
    connect(m_medicineTable, &QTableWidget::cellDoubleClicked, this, &MedicineSelectDialog::onTableDoubleClicked);
    connect(m_selectButton, &QPushButton::clicked, this, &MedicineSelectDialog::onSelectClicked);
    connect(m_cancelButton, &QPushButton::clicked, this, &QDialog::reject);
}

void MedicineSelectDialog::loadMedicines() {
    QJsonObject request;
    // 空请求，获取所有药物
    NetworkClient::instance().sendRequest(MSG_SEARCH_MEDICINES, request);
}

void MedicineSelectDialog::onSearchClicked() {
    QString keyword = m_searchEdit->text().trimmed();
    
    QJsonObject request;
    if (!keyword.isEmpty()) {
        request["keyword"] = keyword;
    }
    
    NetworkClient::instance().sendRequest(MSG_SEARCH_MEDICINES, request);
}

void MedicineSelectDialog::updateMedicineTable(const QJsonArray& medicines) {
    m_medicineTable->setRowCount(0);
    m_medicines = medicines;
    
    for (const QJsonValue& value : medicines) {
        QJsonObject medicineObj = value.toObject();
        
        int row = m_medicineTable->rowCount();
        m_medicineTable->insertRow(row);
        
        m_medicineTable->setItem(row, 0, new QTableWidgetItem(QString::number(medicineObj["id"].toInt())));
        m_medicineTable->setItem(row, 1, new QTableWidgetItem(medicineObj["name"].toString()));
        m_medicineTable->setItem(row, 2, new QTableWidgetItem(medicineObj["specification"].toString()));
        m_medicineTable->setItem(row, 3, new QTableWidgetItem(medicineObj["usage_instruction"].toString()));
        m_medicineTable->setItem(row, 4, new QTableWidgetItem(medicineObj["precautions"].toString()));
    }
    
    // 显示结果数量
    setWindowTitle(QString("选择药物 - 共 %1 条记录").arg(medicines.size()));
}

void MedicineSelectDialog::onTableDoubleClicked(int row, int column) {
    Q_UNUSED(column);
    
    if (row >= 0 && row < m_medicines.size()) {
        QJsonObject medicineObj = m_medicines[row].toObject();
        m_selectedMedicine = Medicine::fromJson(medicineObj);
        accept();  // 关闭对话框并返回Accepted
    }
}

void MedicineSelectDialog::onSelectClicked() {
    int currentRow = m_medicineTable->currentRow();
    
    if (currentRow < 0) {
        QMessageBox::warning(this, "提示", "请选择一个药物");
        return;
    }
    
    if (currentRow >= 0 && currentRow < m_medicines.size()) {
        QJsonObject medicineObj = m_medicines[currentRow].toObject();
        m_selectedMedicine = Medicine::fromJson(medicineObj);
        accept();
    }
}

void MedicineSelectDialog::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_SEARCH_MEDICINES_RESPONSE) {
        if (data["success"].toBool()) {
            updateMedicineTable(data["medicines"].toArray());
        } else {
            QMessageBox::warning(this, "错误", data["message"].toString());
        }
    }
}

